package com.aliyun.heiyu.common.util;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.aliyun.heiyu.common.util.sm.constants.Constants;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import com.aliyun.heiyu.common.util.sm.utils.HexUtil;

/**
 * 国密对称加密算法
 *
 * @author henry
 *
 */
public abstract class SM4Util {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    private static final Charset ENCODING = StandardCharsets.UTF_8;

    public static final String ALGORITHM_NAME = "SM4";

    // 加密算法/分组加密模式/分组填充方式
    // PKCS5Padding-以8个字节为一组进行分组加密
    // 定义分组加密模式使用：PKCS5Padding
    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";

    public static final String ALGORITHM_NAME_CBC_PADDING = "SM4/CBC/PKCS5Padding";

    // 128-32位16进制；256-64位16进制
    public static final int DEFAULT_KEY_SIZE = 128;

    public static final byte[] DEFAULT_KEY = ByteUtils.fromHexString(PropertiesUtil.getValue("jdbcConfig.properties", "privateKey"));
    public static final byte[] DEFAULT_IV = ByteUtils.fromHexString("9446A1C65749AE61FB417D5C67BEDA51");

    /**
     * 生成ECB暗号
     * @explain ECB模式（电子密码本模式：Electronic codebook）
     * @param algorithmName
     *            算法名称
     * @param mode
     *            模式
     * @param key
     * @return
     * @throws Exception
     */
    private static Cipher generateCipherECB(String algorithmName, int mode, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        cipher.init(mode, new SecretKeySpec(key, ALGORITHM_NAME));
        return cipher;
    }

    /**
     * 生成CBC暗号
     * @param algorithmName
     *            算法名称
     * @param mode
     *            模式
     * @param key
     * @param iv
     * @return
     * @throws Exception
     */
    private static Cipher generateCipherCBC(String algorithmName, int mode, byte[] key, byte[] iv) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        cipher.init(mode, new SecretKeySpec(key, ALGORITHM_NAME), new IvParameterSpec(iv));
        return cipher;
    }

    /**
     * 自动生成密钥
     * @explain
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     */
    public static String generateKey() {
        try {
            return HexUtil.byteToHex(generateKey(DEFAULT_KEY_SIZE));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @explain
     * @param keySize
     * @return
     * @throws Exception
     */
    public static byte[] generateKey(int keySize) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME);
        kg.init(keySize, new SecureRandom());
        return kg.generateKey().getEncoded();
    }

    /**
     * 加密模式之Ecb
     * @explain
     * @param key
     * @param data
     * @return
     * @throws Exception
     */
    protected static byte[] encryptECBPadding(byte[] data, byte[] key) throws Exception {
        Cipher cipher = generateCipherECB(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(data);
    }

    /**
     * 解密
     * @explain
     * @param key
     * @param encrypted
     * @return
     * @throws Exception
     */
    protected static byte[] decryptECBPadding(byte[] encrypted, byte[] key) throws Exception {
        Cipher cipher = generateCipherECB(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(encrypted);
    }

    /**
     * 加密模式之cbc
     * @explain
     * @param key
     * @param data
     * @return
     * @throws Exception
     */
    protected static byte[] encryptCBCPadding(byte[] data, byte[] key, byte[] iv) throws Exception {
        Cipher cipher = generateCipherCBC(ALGORITHM_NAME_CBC_PADDING, Cipher.ENCRYPT_MODE, key, iv);
        return cipher.doFinal(data);
    }

    /**
     * 解密
     * @explain
     * @param key
     * @param encrypted
     * @return
     * @throws Exception
     */
    protected static byte[] decryptCBCPadding(byte[] encrypted, byte[] key, byte[] iv) throws Exception {
        Cipher cipher = generateCipherCBC(ALGORITHM_NAME_CBC_PADDING, Cipher.DECRYPT_MODE, key, iv);
        return cipher.doFinal(encrypted);
    }

    /**
     * 加密
     * @explain 加密模式：ECB
     * @param source
     *            待加密字符串
     *            16进制密钥
     * @return 返回16进制的加密字符串
     * @throws Exception
     */
    public static String encrypt(String source) {
        return encrypt(source, ByteUtils.toHexString(DEFAULT_KEY));
    }


    /**
     * 加密
     * @explain 加密模式：ECB
     * @param source
     *            待加密数据
     * @return 返回16进制的加密字符串
     * @throws Exception
     */
    public static String encrypt(byte[] source) {
        return encrypt(source, ByteUtils.toHexString(DEFAULT_KEY));
    }

    /**
     * 加密
     * @explain 加密模式：ECB
     * @param source
     *            待加密字符串
     * @param hexKey
     *            16进制密钥
     * @return 返回16进制的加密字符串
     * @throws Exception
     */
    public static String encrypt(String source, String hexKey) {
        return encrypt(source.getBytes(ENCODING), hexKey);
    }

    /**
     * 加密
     * @explain 加密模式：ECB
     * @param source
     *            待加密字符串
     * @param hexKey
     *            16进制密钥
     * @return 返回16进制的加密字符串
     * @throws Exception
     */
    public static String encrypt(byte[] source, String hexKey) {
        byte[] cipherArray;
        try {
            cipherArray = encryptECBPadding(source, ByteUtils.fromHexString(hexKey));
            return ByteUtils.toHexString(cipherArray);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 解密
     * @explain 解密模式：采用ECB
     * @param encrypted
     *            16进制的加密字符串
     *            16进制密钥
     * @return 解密后的字符串
     * @throws Exception
     */
    public static byte[] decrypt(String encrypted) {
        return decrypt(encrypted, ByteUtils.toHexString(DEFAULT_KEY));
    }

    /**
     * 解密
     * @explain 解密模式：采用ECB
     * @param encrypted
     *            16进制的加密字符串
     *            16进制密钥
     * @return 解密后的字符串
     * @throws Exception
     */
    public static String decryptToString(String encrypted) {
        return decryptToString(encrypted, ByteUtils.toHexString(DEFAULT_KEY));
    }

    /**
     * 解密
     * @explain 解密模式：采用ECB
     * @param encrypted
     *            16进制的加密字符串
     * @param hexKey
     *            16进制密钥
     * @return 解密后的字符串
     * @throws Exception
     */
    public static String decryptToString(String encrypted, String hexKey) {
        return new String(decrypt(encrypted, hexKey), ENCODING);
    }

    /**
     * 解密
     * @explain 解密模式：采用ECB
     * @param encrypted
     *            16进制的加密字符串
     * @param hexKey
     *            16进制密钥
     * @return
     * @throws Exception
     */
    public static byte[] decrypt(String encrypted, String hexKey) {
        try {
            return decryptECBPadding(ByteUtils.fromHexString(encrypted), ByteUtils.fromHexString(hexKey));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encrypted.getBytes(StandardCharsets.UTF_8);
    }

    /**
     * 加密
     * @explain 加密模式：CBC
     * @param source
     *            待加密字符串
     * @param hexKey
     *            16进制密钥
     * @param iv
     *            16进制偏移量
     * @return 返回16进制的加密字符串
     * @throws Exception
     */
    public static String encrypt(String source, String hexKey, String iv) {
        return encrypt(source.getBytes(ENCODING), hexKey, iv);
    }

    /**
     * 加密
     * @explain 加密模式：CBC
     * @param source
     *            待加密字符串
     * @param hexKey
     *            16进制密钥
     * @param iv
     *            16进制偏移量
     * @return 返回16进制的加密字符串
     * @throws Exception
     */
    public static String encrypt(byte[] source, String hexKey, String iv) {
        byte[] cipherArray;
        try {
            cipherArray = encryptCBCPadding(
                source
                ,ByteUtils.fromHexString(hexKey)
                , ByteUtils.fromHexString(iv));
            return ByteUtils.toHexString(cipherArray);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("数据加密失败", e);
        }
    }

    /**
     * 解密
     * @explain 解密模式：采用ECB
     * @param encrypted
     *            16进制的加密字符串
     * @param hexKey
     *            16进制密钥
     * @param iv
     *            16进制偏移量
     * @return 解密后的字符串
     * @throws Exception
     */
    public static String decryptToString(String encrypted, String hexKey, String iv) {
        return new String(decrypt(encrypted, hexKey, iv), ENCODING);
    }

    /**
     * 解密
     * @explain 解密模式：采用ECB
     * @param encrypted
     *            16进制的加密字符串
     * @param hexKey
     *            16进制密钥
     * @param iv
     *            16进制偏移量
     * @return 解密后的字符串
     * @throws Exception
     */
    public static byte[] decrypt(String encrypted, String hexKey, String iv) {
        try {
            if (StringUtils.isBlank(encrypted)) {
                return new byte[] {};
            }

            return decryptCBCPadding(
                ByteUtils.fromHexString(encrypted)
                ,ByteUtils.fromHexString(hexKey)
                , ByteUtils.fromHexString(iv));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encrypted.getBytes(StandardCharsets.UTF_8);
    }

    public static String encrypt_CBC(String data){
        String encrypt = SM4Util.encrypt(data, ByteUtils.toHexString(DEFAULT_KEY), ByteUtils.toHexString(DEFAULT_IV));
        if(encrypt != null){
            return encrypt.toUpperCase();
        }
        return "";
    }

    public static String decrypt_CBC(String data){
        return SM4Util.decryptToString(data,ByteUtils.toHexString(DEFAULT_KEY), ByteUtils.toHexString(DEFAULT_IV));
    }

    public static String decrypt_CBC2(String data){
        return SM4Util.decryptToString(data,ByteUtils.toHexString(Constants.DEFAULT_KEY2), ByteUtils.toHexString(DEFAULT_IV));
    }

    public static String encrypt_CBC2(String data){
        String encrypt = SM4Util.encrypt(data, ByteUtils.toHexString(Constants.DEFAULT_KEY2), ByteUtils.toHexString(DEFAULT_IV));
        if(encrypt != null){
            return encrypt.toUpperCase();
        }
        return "";
    }

    public static String decrypt_CBC2_tran(String data,String key,String iv){
        return SM4Util.decryptToString(data,key, iv);
    }

    public static String encrypt_CBC2_tran(String data,String key,String iv){
        String encrypt = SM4Util.encrypt(data, key, iv);
        if(encrypt != null){
            return encrypt.toUpperCase();
        }
        return "";
    }
}
